package com.lgq.utils;

/**
 *@author  刘光强
 *@date    2012-3-21 下午5:05:37
 *@version 1.0
 *@处理文件上传和储存的工具类
 **/

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadUtil {
	private Map fileField = new TreeMap();
	private Map formField = new TreeMap();
	private int memoryBlock = 2048;
	private File tempFolder = null;
	private boolean multipart = false;
	private HttpServletRequest request = null;
	private final int maxSize = 10240000;

	public FileUploadUtil(File tempFolder, int memeoryBlock) {
		this.tempFolder = tempFolder;
		this.memoryBlock = memeoryBlock;
	}

	public FileUploadUtil() {
	}

	/**
	 * 处理上传文件的方法
	 * 
	 * @param request
	 * @param charset
	 *            编码
	 * @throws FileUploadException
	 */
	public void parse(HttpServletRequest request, String charset)
			throws FileUploadException {
		this.request = request;
		multipart = FileUpload.isMultipartContent(request);
		if (multipart) {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(memoryBlock);
			factory.setRepository(tempFolder);
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setSizeMax(maxSize);
			List items;
			items = upload.parseRequest(request);
			Iterator iterator = items.iterator();
			while (iterator.hasNext()) {
				FileItem item = (FileItem) iterator.next();
				if (item.isFormField()) {
					processFormField(item, charset);
				} else {
					processUploadedFile(item);
				}
			}
		}
	}

	/**
	 * 从单个的item中获取文件并储存
	 * 
	 * @param item
	 * @param charset
	 */
	private void processFormField(FileItem item, String charset) {
		try {
			String name = item.getFieldName();
			String value = item.getString(charset);
			Object objv = formField.get(name);
			if (objv == null) {
				formField.put(name, value);
			} else {
				List values = null;
				if (objv instanceof List) {
					values = (List) objv;
					values.add(value);
				} else {
					String strv = (String) objv;
					values = new ArrayList();
					values.add(strv);
					values.add(value);
				}
				formField.put(name, values);
			}
		} catch (UnsupportedEncodingException e) {
			throw new IllegalArgumentException(
					"the argument \"charset\" missing!");
		}
	}

	private void processUploadedFile(FileItem item) {
		String name = item.getFieldName();
		fileField.put(name, item);
	}

	/**
	 * 写入文件
	 * 
	 * @param item
	 * @param file
	 * @return
	 */
	public static boolean write2file(FileItem item, File file) {
		boolean flag = false;
		try {
			item.write(file);
			flag = true;
		} catch (Exception e) {
		}
		return flag;
	}

	public FileItem getFileItem(String name) {
		if (multipart) {
			return (FileItem) fileField.get(name);
		} else {
			return null;
		}
	}

	public String getParameter(String name) {
		String value = null;
		if (multipart) {
			Object obj = formField.get(name);
			if (obj != null && obj instanceof String) {
				value = (String) obj;
			}
		} else if (request != null) {
			value = request.getParameter(name);
		}
		return value;
	}

	public String[] getParameterValues(String name) {
		String[] values = null;
		if (multipart) {
			Object obj = formField.get(name);
			if (obj != null) {
				if (obj instanceof List) {
					values = (String[]) ((List) obj).toArray(new String[0]);
				} else {
					values = new String[] { (String) obj };
				}
			}
		} else if (request != null) {
			values = request.getParameterValues(name);
		}
		return values;
	}

	public File getRepository() {
		return this.tempFolder;
	}

	public int getSizeThreshold() {
		return this.memoryBlock;
	}

	public boolean isMultipart() {
		return this.multipart;
	}

	public int getMaxSize() {
		return maxSize;
	}

	/**
	 * 删除目录
	 * 
	 * @param folderPath
	 */
	public static void delFolder(String folderPath) {
		if (!new File(folderPath).exists()) {
			return;
		} else {

			try {
				delAllFile(folderPath); // 删除完里面所有内容
				String filePath = folderPath;
				filePath = filePath.toString();
				File myFilePath = new File(filePath);
				myFilePath.delete(); // 删除空文件夹
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 迭代删除文件夹下所有的文件
	 * 
	 * @param path
	 * @return
	 */
	private static boolean delAllFile(String path) {
		boolean flag = false;
		File file = new File(path);
		if (!file.exists()) {
			return flag;
		}
		if (!file.isDirectory()) {
			return flag;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
				delFolder(path + "/" + tempList[i]);// 再删除空文件夹
				flag = true;
			}
		}
		return flag;
	}

	public static boolean createDirIfNoExist(String filepath) {
		File file = new File(filepath);
		if (!file.exists()) {
			boolean ok = false;
			ok = file.mkdir();
			if (!ok) {
				return false;
			}
			return true;
		}
		return true;
	}
}